package com.aivin.lib_readnotes.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.aivin.lib_widget.MaterialButton;
import com.aivin.lib_readnotes.R;
import com.aivin.lib_readnotes.SelectCallBack;
import com.wk.bmoblib.bean.Book;


import java.util.List;
import java.util.Locale;


/**
   要设置这个，否则动画会错乱，比如点击第三个，但是第一个会有动画
    this.setHasStableIds(true); //
     public long getItemId(int position) {
           return position;
     }
 */
public class BookAdapter extends RecyclerView.Adapter {

    private List<Book> books ;
    private SelectCallBack selectCallBack ;

    public BookAdapter(  List<Book> books  , SelectCallBack selectCallBack) {
        this.books = books;
        this.selectCallBack = selectCallBack ;
        this.setHasStableIds(true);
    }

    @NonNull
    @Override
    public ChooseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        View view =   LayoutInflater.from(context).inflate(R.layout.libenglish_item_txt_choose, parent, false);
        return new ChooseHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        Book bean = books.get(position);
        final ChooseHolder chooseHolder = (ChooseHolder)holder;
        chooseHolder.item_txt.setText( String.format(Locale.getDefault(),"%d、%s",position+1 ,bean.getBookName()) );

    }



    @Override
    public int getItemCount() {
        return books==null? 0: books.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

     private class ChooseHolder extends RecyclerView.ViewHolder {

        private MaterialButton item_txt;
         private ChooseHolder(View itemView){
            super(itemView);
            item_txt =  itemView.findViewById(R.id.item_txt);
            View.OnClickListener clickListener = v -> {
                int mSelectedItem = getAdapterPosition();
                selectCallBack.onSelected(books.get(mSelectedItem)  ,mSelectedItem);
                notifyDataSetChanged() ;
            };
            item_txt.setOnClickListener(clickListener);

        }
    }


}
